// pages/add-share/index.js
var api = require('../../api.js');
let time = require('../../utils/utils.js');
var apple = require('../../app.js');
var inviteCode = ''

var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    items: [
      { name: '0', value: '男', checked: true },
      { name: '1', value: '女' },
  
    ],
    gender:0,
    seleted: "",
    imgServer: api.default.img_server,
    form: {
      nickname: '',
      gender: 0,
      phone: '',
      job: '',
      birthday: Date,
      city: '',
    },
    img: "/images/img-share-un.png",
    agree: 0,
    birthdayisEmpty:true,
    canChange:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var page = this;
    var user_info = wx.getStorageSync("user_info");
    var my_info = wx.getStorageSync("my_info");
    inviteCode = wx.getStorageSync("inviteCode");
    console.log("register invite========"+inviteCode)
    if(my_info.birthday !='' & my_info.birthday != undefined){
      page.setData({
        birthdayisEmpty:false,
        canChange:true,
      })
      if(my_info.gender != undefined && my_info.gender !=''&& my_info.gender ==1){
        page.setData({
          'items[1].checked': true
        })
      }
    }

    page.setData({
      'form.gender': my_info.gender, 
      'form.phone': my_info.phone, 
      'form.job': my_info.job, 
      'form.birthday': time.formatTimeTwo(my_info.birthday, 'Y-M-D'), 
      'form.city': my_info.city, 
    })
    if (my_info.city != undefined && my_info.city != '' && my_info.city != null){
      page.setData({
        'form.nickname': my_info.nickname
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var page = this;
    var user_info = wx.getStorageSync("user_info");
    var store = wx.getStorageSync("store");
    var share_setting = wx.getStorageSync("share_setting");
    page.setData({
      user_info: user_info,
      store: store,
      share_setting: share_setting
    });

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  //普通选择器：
  bindDateChange: function (e) {
    var page = this;
    console.log(e.detail.value)
    page.setData({
      'form.birthday': e.detail.value, 
      birthdayisEmpty: false
    })
  },
  
  radioChange: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    let value = e.detail.value;
    this.data.gender = e.detail.value;
    this.setData({
      'form.gender': value, 
    })
  },
  formSubmit: function (e) {
    var page = this;
    var user_info = wx.getStorageSync("user_info");
    var my_info = wx.getStorageSync("my_info");
    console.log(my_info);
    page.data.form = e.detail.value;
    if (this.isBlank(page.data.form.nickname)) {
      return;
    };
    if (page.data.form.gender == undefined ||page.data.form.gender =='') {
      page.data.form.gender = 0
    };
    if (!this.isPhone(page.data.form.phone)) {
      return;
    };
    if (this.isBlank(page.data.form.job)) {
      return;
    };
    if (this.isBlank(page.data.form.city)) {
      return;
    };
    console.log(page.data.agree);
    var test = e.detail.value;
    console.log(wx.getStorageSync("my_info"));
    test.wxId = wx.getStorageSync("access_token");
    test.id = wx.getStorageSync("my_info").id;
    test.birthday = new Date(test.birthday);
    test.gender = page.data.gender;
    console.log("test");
    console.log(test);
    if(inviteCode != undefined & inviteCode != ''){
      test.invitecode = inviteCode;
    }
    test.invitecode = "182";


    app.request({
      url: api.order.updateMember,
      method: 'POST',
      data: test,
      success: function (res) {
        console.log(res)
        if (res.code == 200) {
          user_info.is_distributor = 2;
          wx.setStorageSync(
            "user_info", user_info
          );
          // app.login();


          wx.login({
            success: function (res) {
              if (res.code) {
                var code = res.code;
                console.log(res)
                getApp().loginrequest({
                  url: api.passport.quick_login,
                  method: "post",
                  data: {
                    code: code
                  },
                  success: function (res) {
                    console.log("quickLoginSuccessful")
                    console.log(res)
                    wx.hideLoading();
                    if (res.code == 200) {
                      const tokenStr = res.data.tokenHead + res.data.token
                      wx.setStorageSync('loginToken', tokenStr)
                      wx.setStorageSync('token', res.data.token);
                      wx.setStorageSync("access_token", res.data.userId);
                      wx.setStorageSync("user_info", {
                        avatar_url: res.data.img,
                        nickname: res.data.username,
                        avatar_url: res.data.icon,
                        // parent: res.data.parent,
                        id: res.data.id
                      });
                      wx.setStorageSync("my_info", {
                        supplyId: res.data.myInfo.supplyId,
                        supplyState: res.data.myInfo.supplyState,
                        myMoney: res.data.myInfo.myMoney,
                        icon: res.data.myInfo.icon,
                        nickname: res.data.myInfo.nickname,
                        memberLevelId: res.data.myInfo.memberLevelId,
                        id: res.data.myInfo.id,
                        city: res.data.myInfo.city,
                        gender: res.data.myInfo.gender,
                        job: res.data.myInfo.job,
                        phone: res.data.myInfo.phone,
                        birthday: res.data.myInfo.birthday,
                        // parent: res.data.parent,
                      });

                      wx.showModal({
                        title: '',
                        content: '恭喜您成为真食坊土垚级会员，感恩真食坊成长路上有您的陪伴和支持。',
                        showCancel: false,//是否显示取消按钮
                        confirmText: "确定",//默认是“确定”
                        confirmColor: 'skyblue',//确定文字的颜色
                        success: function (res) {
                          if (res.cancel) {
                            //点击取消,默认隐藏弹框
                          } else {
                            //点击确定
                            wx.navigateBack({
                              delta: 1
                            })
                          }
                        },
                        fail: function (res) { },//接口调用失败的回调函数
                        complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
                      })

                    

                    } 
                  }
                });
              }


            }
          });


        } else {
          wx.showModal({
            content: res.msg,
            showCancel: false,
          })
       
        }
      }
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
 


 

  // 手机验证
  isPhone: function (phone) {
    if (!(/^1[2345789]\d{9}$/.test(phone))) {
      wx.showModal({
        content: "手机号码格式错误!",
        showCancel: false,
      })
      return false
    } else {
      return true
    }
  },
  isBlank: function (text) {
    console.log(text)
    if (text == undefined || text == '') {
      wx.showModal({
        content: "有必填项未填写!",
        showCancel: false,
      })
      return true
    }
    return false
  }
})